package org.vison.wonfu.framework.codestyle.rules.impl;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import org.vison.wonfu.framework.codestyle.config.CheckerConfig;
import org.vison.wonfu.framework.codestyle.issue.Issue;
import org.vison.wonfu.framework.codestyle.issue.IssueCollector;
import org.vison.wonfu.framework.codestyle.rules.CodeCheckRule;


import java.io.File;

/**
 * 方法长度检查规则：检查方法是否过长
 */
public class MethodLengthCheckRule implements CodeCheckRule {
    private static final String RULE_ID = "method-length-check";
    private static final String RULE_NAME = "方法长度检查";
    private static final String RULE_DESCRIPTION = "检查方法是否超过指定的最大行数限制";
    
    private boolean enabled = true;
    private int maxMethodLength = 50; // 默认最大方法长度
    private boolean strict = false;
    
    @Override
    public String getId() {
        return RULE_ID;
    }
    
    @Override
    public String getName() {
        return RULE_NAME;
    }
    
    @Override
    public String getDescription() {
        return RULE_DESCRIPTION;
    }
    
    @Override
    public void initialize(CheckerConfig config) {
        this.enabled = config.isRuleEnabled(RULE_ID);
        // 从配置中获取最大方法长度，默认为50
        this.maxMethodLength = config.getRuleProperty(
                RULE_ID, "maxLength", Integer.class, 50);
        this.strict = config.getRuleConfig(RULE_ID).isStrict();
    }

    @Override
    public boolean isStrict() {
        return strict;
    }


    
    @Override
    public void check(File file, CompilationUnit compilationUnit, IssueCollector collector) {
        if (!enabled) {
            return;
        }
        // 检查所有方法的长度
        compilationUnit.accept(new VoidVisitorAdapter<Void>() {
            @Override
            public void visit(MethodDeclaration n, Void arg) {
                super.visit(n, arg);
                
                if (n.getRange().isPresent()) {
                    int startLine = n.getRange().get().begin.line;
                    int endLine = n.getRange().get().end.line;
                    int methodLength = endLine - startLine + 1;
                    
                    if (methodLength > maxMethodLength) {
                        collector.addIssue(new Issue(
                                file,
                                startLine,
                                RULE_ID,
                                "方法 '" + n.getNameAsString() + "' 过长(" + methodLength + "行)，超过最大限制(" + maxMethodLength + "行)",
                                Issue.Severity.WARNING
                        ));
                    }
                }
            }
        }, null);
    }
}
